<?php
namespace app\myadmin\controller;
use think\Db;
class Article extends Base
{
	// 列表
    public function index()
    {
    	if($this->request->isPost()) {
    	    $post = $this->request->post();
    		$res=Model("Article")->index($post);
    		return $res;
    	} else {
    	    return view();
    	}
    }
	// 增改
	public function edit()
	{
		$id = $this->request->has("id") ? $this->request->param("id", 0, "intval") : 0;
		$info=Db::name("article")->where("id",$id)->find();
		$info=$this->thumbs($info);
		if($this->request->isPost()) {
		    $post = $this->request->post();
			$res=Model("Article")->edit($id,$post);
			return $res;
		} else {
			return view("", [
				"info"		=>$info
			]);
		}
	}
	// 删除
	public function del()
	{
		if($this->request->isPost()) {
		    $post = $this->request->post("id");
			$res=DelTable($post,"article");
			return $res;
		}
	}
	// 状态
	public function status()
	{
		if($this->request->isPost()) {
		   $post = $this->request->post();
		   $res=ChangeTable($post,"article");
		   return $res;
		}
	}
	// 置顶
	public function top()
	{
		if($this->request->isPost()) {
		   $post = $this->request->post();
		   $res=ChangeTable($post,"article");
		   return $res;
		}
	}
	// 上传
	public function upload()
	{
		$file = request()->file("file");
		$res=UploadThumb($file);
		return json_encode($res,JSON_UNESCAPED_UNICODE);
	}
	// 图片遍历
	private function thumbs($data)
	{
		if($data){
			// 多张图片遍历，去掉没用的
			if($data["image"]){
				$newdata=[];
				$data["images"]=$data["image"]?explode(",",$data["image"]):"";
				foreach($data["images"] as $k=>$v){
					$file=Db::name("files")->where("id",$v)->field("id,name,topic,size")->find();
					if($file){
						$data["images"][$k]=$file;
						array_push($newdata,$v);
					}else{
						unset($data["images"][$k]);
					}
				}
				$data["image"]=implode(",",$newdata);
			}
		}
		return $data;
	}
}
